package server;

import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Map<String,Class> servletMap;
    private Request request;
    private Response response;
    private  String projectName;
    public RequestProcessor(Socket socket, Map<String, Class> servletMap,Request request,Response response,String projectName) {
        this.socket = socket;
        this.servletMap = servletMap;
        this.request = request;
        this.response = response;
        this.projectName = projectName;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
           // Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
           String paramPath=request.getUrl().replaceAll("/"+projectName,"");
            // 静态资源处理
            if(servletMap.get(paramPath) == null) {
                response.outputHtml(paramPath,projectName);
            }else{
                // 动态资源servlet请求
//                HttpServlet httpServlet = servletMap.get(request.getUrl());
//                httpServlet.service(request,response);
              //  System.out.println(request.getUrl());
                String key=request.getUrl().replaceAll("/"+projectName,"");
                Class httpServlet=servletMap.get(key);
                Method method=httpServlet.getMethod("service",new Class[]{Request.class,Response.class});
                method.setAccessible(true);
                method.invoke(httpServlet.getDeclaredConstructor().newInstance(),request,response);
            }

            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
